package com.nuanshui.heatedloan.util;

import java.io.InputStream;
import java.util.HashMap;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.springframework.expression.EvaluationContext;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.common.TemplateParserContext;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;


/**
 * 读取xml文件中原生sql或hql的工具类<br>
 * 
 */
public class ReadSqlUtil {

	/**
	 * 放置Dom4j的Document对象
	 */
	private static HashMap<String, Document> documentMap = new HashMap<String, Document>();
	private static EvaluationContext context = new StandardEvaluationContext();
	private static ExpressionParser parser = new SpelExpressionParser();
	

	private ReadSqlUtil() {
	}

	private static class SingletonFactory {
		private static ReadSqlUtil instance = new ReadSqlUtil();
	}

	public static ReadSqlUtil getInstance() {
		return SingletonFactory.instance;
	}

	/**
	 * 指定读取那个配置文件中的哪个节点中的sql
	 */
	public String readSql(final String name,final String elementName) {
		if (!documentMap.containsKey(name)) {
			final SAXReader reader = new SAXReader();
			Document document = null;
			try {
				final InputStream inputStream = ReadSqlUtil.class
						.getResourceAsStream("/nativesql/" + name + "");
				document = reader.read(inputStream);
				inputStream.close();
				
				final Element root = document.getRootElement();
				final Element memberElm = root.element(elementName);
				//context.setVariable("database", GlobalParam.DB_SCHEMA);
				String str = parser.parseExpression(memberElm.getText(), new TemplateParserContext("{", "}")).getValue(context, String.class);
				memberElm.setText(str);
				documentMap.put(name, document);
				return memberElm.getText();
			}
			catch (final Exception e) {
				e.printStackTrace();
			}
		} else {
			final Element root = documentMap.get(name).getRootElement();
			final Element memberElm = root.element(elementName);
			String content =  memberElm.getText();
		//	context.setVariable("database", GlobalParam.DB_SCHEMA);
			String str = parser.parseExpression(content, new TemplateParserContext("{", "}")).getValue(context, String.class);
		
			return str;
		}
		return null;
	}
}
